<template>
  <div class="app-container">
    <!--步骤条组件 -->
    <el-steps :active="activeStep" finish-status="success" space="500px" align-center>
      <el-step title="商品信息"></el-step>
      <el-step title="商品详情"></el-step>
      <el-step title="其他设置"></el-step>
    </el-steps>

    <!-- 步骤内容区域 -->
    <div class="steps-content">
      <!-- 步骤 1：商品信息 -->
      <div v-if="activeStep === 0">
        <el-form :model="productForm" :rules="rules" label-width="120px" ref="productFormRef">
          <el-row>
            <el-col :span="12"><el-form-item label="商品名称:" prop="storeName">
                <el-input v-model="productForm.storeName" placeholder="请输入商品名称"></el-input> </el-form-item></el-col>
            <el-col :span="12">
              <el-form-item label="商品分类:" prop="cateId">
                <el-cascader :options="categoryOption" :props="cascaderProps" collapse-tags clearable
                  placeholder="请选择商品分类" @change="handleCategoryChange"></el-cascader>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row>
            <el-col :span="12"><el-form-item label="商品关键字:" prop="keyword">
                <el-input v-model="productForm.keyword" placeholder="请输入商品关键字"></el-input> </el-form-item></el-col>
            <el-col :span="12">
              <el-form-item label="单位:" prop="unitName">
                <el-input v-model="productForm.unitName" placeholder="请输入单位"></el-input> </el-form-item></el-col>
          </el-row>
          <el-row>
            <el-col :span="12"><el-form-item label="商品简介:" prop="storeInfo">
                <el-input type="textarea" v-model="productForm.storeInfo" placeholder="请输入商品简介"></el-input>
              </el-form-item></el-col>
          </el-row>

          <el-form-item label="商品封面图:" prop="image">
            <ImageUpload v-model="productForm.image" :isShowTip="false" :limit="1" />
          </el-form-item>
          <el-form-item label="商品轮播图:" prop="sliderImage">
            <ImageUpload v-model="productForm.sliderImage" :isShowTip="false" />
          </el-form-item>
          <el-form-item label="运费模板:" prop="isPostage">
            <el-select v-model="productForm.isPostage" placeholder="请选择">
              <el-option label="全国包邮" :value=0></el-option>
              <el-option label="不包邮" :value=1></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="运费:" prop="postage">
            <el-input-number v-model="productForm.postage" :min="0" :disabled="productForm.isPostage === 0" />
          </el-form-item>
          <el-form-item label="商品规格:">
            <el-radio-group v-model="productForm.specType">
              <el-radio :label="0">单规格</el-radio>
              <el-radio :label="1">多规格</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-row>
            <el-col :span="24">
              <!-- 多规格操作区域 -->
              <div v-if="productForm.specType === 1" class="spec-operation">
                <el-form-item label="商品规格:">
                  <el-select v-model="selectedSpec" placeholder="请选择" size="small" style="width: 180px">
                    <el-option v-for="item in cascaderAttrData" :key="item.id" :label="item.ruleName"
                      :value="item.id"></el-option>
                  </el-select>
                  <el-button type="primary" size="small" @click="confirmSpec">确认</el-button>
                  <el-button size="small" @click="openAddSpecDialog">添加规格</el-button>
                </el-form-item>

                <!-- 已选规格列表 -->
                <div class="spec-list w-full">
                  <div v-for="(specGroup, groupIndex) in selectedSpecGroups" :key="groupIndex" class="spec-item">
                    <h3 class="spec-name">{{ specGroup.spec }}：</h3>
                    <el-tag v-for="(value, valueIndex) in specGroup.values" :key="valueIndex" size="small" closable
                      @close="removeSpecValue(groupIndex, valueIndex)" class="spec-tag">
                      {{ value }}
                    </el-tag>
                    <el-button type="text" size="small" class="add-btn" @click="openAddSpecValueDialog(groupIndex)">
                      <i class="fa fa-plus-circle"></i> 添加
                    </el-button>
                    <el-button type="text" size="small" class="delete-btn" @click="removeSpecGroup(groupIndex)">
                      <i class="fa fa-trash"></i> 删除
                    </el-button>
                  </div>
                </div>

                <!-- 批量设置 -->
                <div v-if="productForm.specType === 1 && showSpecTable" style="margin-bottom: 16px;">
                  <el-form-item label="批量设置：" style="margin-bottom: 16px;">
                    <el-table :data="[batchForm]" border>
                      <el-table-column prop="tableImage" label="图片" align="center" width="95px">
                        <template>
                          <ImageUpload v-model="batchForm.tableImage" :isShowTip="false" :limit="1" />
                        </template>
                      </el-table-column>
                      <el-table-column prop="price" label="售价" align="center">
                        <template>
                          <el-input-number v-model="batchForm.price" :min="0" :step="1" :precision="2"
                            style="width: 120px;" />
                        </template>
                      </el-table-column>
                      <el-table-column prop="cost" label="成本价" align="center">
                        <template>
                          <el-input-number v-model="batchForm.cost" :min="0" :step="1" :precision="2"
                            style="width: 120px;" />
                        </template>
                      </el-table-column>
                      <el-table-column prop="otPrice" label="原价" align="center">
                        <template>
                          <el-input-number v-model="batchForm.otPrice" :min="0" :step="1" :precision="2"
                            style="width: 120px;" />
                        </template>
                      </el-table-column>
                      <el-table-column prop="stock" label="库存" align="center">
                        <template>
                          <el-input-number v-model="batchForm.stock" :min="0" :step="1" :precision="0"
                            style="width: 120px;" />
                        </template>
                      </el-table-column>
                      <el-table-column prop="weight" label="重量（KG）" align="center">
                        <template>
                          <el-input-number v-model="batchForm.weight" :min="0" :step="1" :precision="2"
                            style="width: 120px;" />
                        </template>
                      </el-table-column>
                      <el-table-column prop="volume" label="体积(m³)" align="center">
                        <template>
                          <el-input-number v-model="batchForm.volume" :min="0" :step="1" :precision="2"
                            style="width: 120px;" />
                        </template>
                      </el-table-column>
                      <el-table-column label="操作" align="center" width="100">
                        <template>
                          <el-button type="text" @click="handleBatchSet" style="color: #409EFF;">批量添加</el-button>
                        </template>
                      </el-table-column>
                    </el-table>
                  </el-form-item>
                </div>
              </div>

              <!-- 添加规格弹窗 -->
              <el-dialog title="添加规格" :visible.sync="addSpecDialogVisible" width="30%"
                :before-close="handleAddSpecClose">
                <el-form :model="addSpecForm" label-width="80px">
                  <el-form-item label="规格">
                    <el-input v-model="addSpecForm.spec" placeholder="请输入规格名称"></el-input>
                  </el-form-item>
                  <el-form-item label="规格值">
                    <el-input v-model="addSpecForm.value" placeholder="请输入规格值"></el-input>
                  </el-form-item>
                </el-form>
                <template #footer>
                  <span class="dialog-footer">
                    <el-button @click="addSpecDialogVisible = false">取消</el-button>
                    <el-button type="primary" @click="confirmAddSpec">确认</el-button>
                  </span>
                </template>
              </el-dialog>

              <!-- 添加规格值弹窗 -->
              <el-dialog title="添加规格值" :visible.sync="addSpecValueDialogVisible" width="30%"
                :before-close="handleAddSpecValueClose">
                <el-form :model="addSpecValueForm" label-width="80px">
                  <el-form-item label="规格值">
                    <el-input v-model="addSpecValueForm.value" placeholder="请输入规格值"></el-input>
                  </el-form-item>
                </el-form>
                <template #footer>
                  <span class="dialog-footer">
                    <el-button @click="addSpecValueDialogVisible = false">取消</el-button>
                    <el-button type="primary" @click="confirmAddSpecValue">确认</el-button>
                  </span>
                </template>
              </el-dialog>

              <!-- 删除规格确认弹窗 -->
              <el-dialog title="确认删除" :visible.sync="deleteDialogVisible" width="30%" :before-close="handleDeleteClose">
                <div slot="content">
                  确定要删除规格"{{ deletingSpec }}"吗？
                </div>
                <template #footer>
                  <span class="dialog-footer">
                    <el-button @click="deleteDialogVisible = false">取消</el-button>
                    <el-button type="danger" @click="confirmDeleteSpec">确认删除</el-button>
                  </span>
                </template>
              </el-dialog>

              <!-- 表格区域 -->
              <div class="mt-6 center-table">
                <!-- 单规格 -->
                <el-table v-if="productForm.specType === 0" :data="tableData" border>
                  <el-table-column prop="tableImage" label="图片" width="100px">
                    <template slot-scope="scope">
                      <ImageUpload v-model="scope.row.tableImage" :isShowTip="false" :limit="1" />
                    </template>
                  </el-table-column>
                  <el-table-column prop="price" label="售价">
                    <template slot-scope="scope">
                      <el-input-number v-model="scope.row.price" :min="0" :step="1" :precision="2" placeholder="0"
                        style="width: 100%;" @keydown.native="numberKeydown($event)"></el-input-number>
                    </template>
                  </el-table-column>
                  <el-table-column prop="cost" label="成本价">
                    <template slot-scope="scope">
                      <el-input-number v-model="scope.row.cost" :min="0" :step="1" :precision="2" placeholder="0"
                        style="width: 100%;" @keydown.native="numberKeydown($event)"></el-input-number>
                    </template>
                  </el-table-column>
                  <el-table-column prop="otPrice" label="原价">
                    <template slot-scope="scope">
                      <el-input-number v-model="scope.row.otPrice" :min="0" :step="1" :precision="2" placeholder="0"
                        style="width: 100%;" @keydown.native="numberKeydown($event)"></el-input-number>
                    </template>
                  </el-table-column>
                  <el-table-column prop="stock" label="库存">
                    <template slot-scope="scope">
                      <el-input-number v-model="scope.row.stock" :min="0" :step="1" :precision="0" placeholder="0"
                        style="width: 100%;" @keydown.native="numberKeydown($event)"></el-input-number>
                    </template>
                  </el-table-column>
                  <el-table-column prop="weight" label="重量（KG）">
                    <template slot-scope="scope">
                      <el-input-number v-model="scope.row.weight" :min="0" :step="1" :precision="2" placeholder="0"
                        style="width: 100%;" @keydown.native="numberKeydown($event)"></el-input-number>
                    </template>
                  </el-table-column>
                  <el-table-column prop="volume" label="体积(m³)">
                    <template slot-scope="scope">
                      <el-input-number v-model="scope.row.volume" :min="0" :step="1" :precision="2" placeholder="0"
                        style="width: 100%;" @keydown.native="numberKeydown($event)"></el-input-number>
                    </template>
                  </el-table-column>
                  <el-table-column prop="productNo" label="商品编号" v-if="false">
                    <template slot-scope="scope">
                      <el-input v-model="scope.row.productNo" placeholder=""></el-input>
                    </template>
                  </el-table-column>
                </el-table>

                <!-- 多规格 -->
                <el-table :data="multipleSpecTableData" border size="small" style="width: 100%"
                  v-if="productForm.specType === 1 && showSpecTable">
                  <!-- 动态生成规格列 -->
                  <el-table-column v-for="specGroup in selectedSpecGroups" :key="specGroup.spec.toString()"
                    :prop="specGroup.spec.toString()" :label="specGroup.spec.toString()" width="100px"></el-table-column>
                  <el-table-column prop="tableImage" label="图片" width="85px">
                    <template slot-scope="scope">
                      <ImageUpload v-model="scope.row.tableImage" :isShowTip="false" :limit="1" />
                    </template>
                  </el-table-column>
                  <el-table-column prop="price" label="售价">
                    <template slot-scope="scope">
                      <el-input-number v-model="scope.row.price" :min="0" :step="1" :precision="2" placeholder="0"
                        style="width: 100%;" @keydown.native="numberKeydown($event)"></el-input-number>
                    </template>
                  </el-table-column>
                  <el-table-column prop="cost" label="成本价">
                    <template slot-scope="scope">
                      <el-input-number v-model="scope.row.cost" :min="0" :step="1" :precision="2" placeholder="0"
                        style="width: 100%;" @keydown.native="numberKeydown($event)"></el-input-number>
                    </template>
                  </el-table-column>
                  <el-table-column prop="otPrice" label="原价">
                    <template slot-scope="scope">
                      <el-input-number v-model="scope.row.otPrice" :min="0" :step="1" :precision="2" placeholder="0"
                        style="width: 100%;" @keydown.native="numberKeydown($event)"></el-input-number>
                    </template>
                  </el-table-column>
                  <el-table-column prop="stock" label="库存">
                    <template slot-scope="scope">
                      <el-input-number v-model="scope.row.stock" :min="0" :step="1" :precision="0" placeholder="0"
                        style="width: 100%;" @keydown.native="numberKeydown($event)"></el-input-number>
                    </template>
                  </el-table-column>
                  <el-table-column prop="weight" label="重量（KG）">
                    <template slot-scope="scope">
                      <el-input-number v-model="scope.row.weight" :min="0" :step="1" :precision="2" placeholder="0"
                        style="width: 100%;" @keydown.native="numberKeydown($event)"></el-input-number>
                    </template>
                  </el-table-column>
                  <el-table-column prop="volume" label="体积(m³)">
                    <template slot-scope="scope">
                      <el-input-number v-model="scope.row.volume" :min="0" :step="1" :precision="2" placeholder="0"
                        style="width: 100%;" @keydown.native="numberKeydown($event)"></el-input-number>
                    </template>
                  </el-table-column>
                  <el-table-column prop="productNo" label="商品编号" v-if="false">
                    <template slot-scope="scope">
                      <el-input v-model="scope.row.productNo" placeholder=""></el-input>
                    </template>
                  </el-table-column>
                </el-table>
              </div>
            </el-col>
          </el-row>
          <el-form-item>
            <el-button type="primary" @click="handleNext">下一步</el-button>
          </el-form-item>
        </el-form>
      </div>

      <!-- 步骤 2：商品详情 -->
      <div v-else-if="activeStep === 1">
        <div class="detail-upload-area large-upload">
          <ImageUpload v-model="detailImage" :isShowTip="false" />
        </div>
        <el-button type="primary" @click="handlePrev">上一步</el-button>
        <el-button type="primary" @click="handleNext">下一步</el-button>
      </div>

      <!-- 步骤 3：其他设置 -->
      <div v-else>
        <el-form :model="productForm" label-width="120px">
          <div class="product-info">
            <el-row>
              <el-col :span="8"> <!-- 排序 -->
                <el-form-item label="排序">
                  <el-input-number v-model="productForm.sort" :min="0" :step="1"></el-input-number>
                </el-form-item></el-col>
              <el-col :span="8"> <!-- 积分 -->
                <el-form-item label="积分">
                  <el-input-number v-model="productForm.giveIntegral" :min="0" :step="1"></el-input-number>
                </el-form-item></el-col>
              <el-col :span="8"> <!-- 虚拟销量 -->
                <el-form-item label="虚拟销量">
                  <el-input-number v-model="productForm.ficti" :min="0" :step="1"></el-input-number>
                </el-form-item></el-col>
            </el-row>
            <!-- 商品推荐 -->
            <el-form-item label="商品推荐">
              <el-checkbox-group v-model="recommendTypes" @change="handleRecommendChange">
                <el-checkbox label="isHot">是否热卖</el-checkbox>
                <el-checkbox label="isGood">热门榜单</el-checkbox>
                <el-checkbox label="isBenefit">促销单品</el-checkbox>
                <el-checkbox label="isBest">精品推荐</el-checkbox>
                <el-checkbox label="isNew">首发新品</el-checkbox>
              </el-checkbox-group>
            </el-form-item>

            <!-- 活动优先级 -->
            <el-form-item label="活动优先级">
              <!-- 可拖拽的按钮容器 -->
              <div class="button-group" ref="buttonGroup">
                <el-button v-for="item in buttonList" :key="item.key" :type="item.type"
                  style="margin-right: 8px;">
                  {{ item.label }}
                </el-button>
              </div>
              <div class="tip">可拖动按钮调整活动的优先展示顺序</div>
            </el-form-item>
          </div>
          <el-form-item>
            <el-button type="primary" @click="handlePrev">上一步</el-button>
            <el-button type="primary" @click="handleSubmit">提交</el-button>
          </el-form-item>
        </el-form>
      </div>

    </div>
  </div>
</template>

<script>
import * as ProductApi from "@/api/store/storeproduct";
import * as CategoryApi from "@/api/store/category";
import * as ProductRuleApi from '@/api/store/rule';
import ImageUpload from "@/components/ImageUpload";
import Sortable from 'sortablejs' // 引入 Sortable
export default {
  name: "ProductForm",
  components: { ImageUpload },
  data() {
    return {
      //其他设置
      buttonList: [
        { label: '默认', type: 'danger', key: 0 },
        { label: '秒杀', type: 'primary', key: 1 },
        { label: '砍价', type: 'success', key: 2 },
        { label: '拼团', type: 'warning', key: 3 }
      ],

      recommendTypes: [],
      selectedSpec: '',
      selectedSpecGroups: [],
      addSpecDialogVisible: false,
      addSpecForm: {
        spec: '',
        value: ''
      },
      addSpecValueDialogVisible: false,
      addSpecValueForm: {
        value: ''
      },
      deleteDialogVisible: false,
      deletingSpec: '',
      deletingIndex: -1,
      currentGroupIndex: -1,
      multipleSpecTableData: [],

      attrOptions: [],
      value: '',
      cascaderProps: {
        multiple: true,
        checkStrictly: false,
        emitPath: true,
        label: 'label',
        value: 'value',
        children: 'children'
      },
      categoryOption: [], // 级联选择器所需的层级数据
      activeStep: 0,//步骤
      //商品表单
      productForm: {
        activity: "",//活动优先级
        isHot: 0,//是否热卖
        isNew: 0,//首发新品
        isBest: 0,//精品推荐
        isBenefit: 0,//促销单品
        isGood: 0,//热门榜单
        ficti: 0,//虚拟销量
        giveIntegral: 0,//积分
        sort: 0,//排序
        storeName: "",//商品名称
        cateId: "",//商品分类
        keyword: "",//商品关键字
        unitName: "",//单位
        storeInfo: "",//商品简介
        image: [],//商品封面图 - 初始化为数组
        sliderImage: [],//商品轮播图 - 初始化为数组
        specType: 0,//商品规格
        vipPrice: 0,//vip价格
        postage: 0,//运费
        isPostage: 0,//是否包邮
        price: 0,//商品价格
        cost: 0,//成本价
        otPrice: 0,//市场价
        stock: 0,//库存
      },
      //单规格数据
      tableData: [
        {
          tableImage: "",//单规格图片 - 初始化为数组
          price: 0,//商品价格
          cost: 0,//成本价
          otPrice: 0,//市场价
          stock: 0,//库存
          productNo: null,//商品编号
          weight: 0,//重量
          volume: 0,//体积
        }
      ],
      detailImage: [],
      // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
      formLoading: false,
      // 表单校验
      rules: {
        storeName: [
          { required: true, message: "请输入商品名称", trigger: "blur" },
        ],
        cateId: [
          { required: true, message: "请选择商品分类", trigger: "change" },
        ],
        keyword: [
          { required: true, message: "请输入商品关键字", trigger: "blur" },
        ],
        unitName: [{ required: true, message: "请输入单位", trigger: "blur" }],
        storeInfo: [
          { required: true, message: "请输入商品简介", trigger: "blur" },
        ],
        image: [
          { required: true, message: "请上传商品封面图", trigger: "change" }
        ],
        sliderImage: [
          { required: true, message: "请上传商品轮播图", trigger: "change" }
        ],
        isPostage: [
          { required: true, message: "请选择运费模板", trigger: "change" }
        ],
      },
      cascaderAttrData: [],
      batchForm: {
        tableImage: "",
        price: null,
        cost: null,
        otPrice: null,
        stock: null,
        weight: null,
        volume: null
      },
      showSpecTable: false,
    };
  },
  created() {
    //重置数据
    this.reset();
    this.getCategoryList();
    this.handleAttrData();
  },
  watch: {
    'productForm.isPostage'(val) {
      if (val === 0) {
        this.productForm.postage = 0;
      }
    },
    // 监听步骤变化，当切换到步骤3时初始化Sortable
    activeStep(newStep) {
      if (newStep === 2) {
        this.$nextTick(() => {
          this.initSortable();
        });
      }
    }
  },
  computed: {
    // 动态获取所有已选规格
    allSelectedSpecs() {
      return this.selectedSpecGroups.map(group => group.spec);
    }
  },
  methods: {
    //活动优先级
    initSortable() {
      // 检查DOM元素是否存在
      if (!this.$refs.buttonGroup) {
        console.warn('buttonGroup ref not found, skipping Sortable initialization');
        return;
      }

      // 1. 配置Sortable
      const sortable = new Sortable(this.$refs.buttonGroup, {
        animation: 10, // 拖拽动画时长
        onEnd: (evt) => {
          // 2. 拖拽结束后更新数组顺序
          const movedItem = this.buttonList.splice(evt.oldIndex, 1)[0];
          this.buttonList.splice(evt.newIndex, 0, movedItem);

          //清空活动优先级
          this.productForm.activity = "";
          const activityKeys = [];
          this.buttonList.forEach(item => {
            //存储活动优先级
            activityKeys.push(item.key);
          });
          this.productForm.activity = activityKeys.join(',');
        }
      });
    },

    // 处理推荐类型变更
    handleRecommendChange(values) {
      // 先将所有推荐类型重置为 0
      this.productForm.isHot = 0;
      this.productForm.isGood = 0;
      this.productForm.isBenefit = 0;
      this.productForm.isBest = 0;
      this.productForm.isNew = 0;

      // 将选中的值设为 1
      values.forEach(key => {
        this.productForm[key] = 1;
      });
    },

    handleDragStart(event, index) {
      event.dataTransfer.setData('index', index);
    },
    handleDrop(event, targetIndex) {
      const sourceIndex = Number(event.dataTransfer.getData('index'));
      const [removed] = this.priorityButtons.splice(sourceIndex, 1);
      this.priorityButtons.splice(targetIndex, 0, removed);
    },

    handleSpecTypeChange(type) {
      this.productForm.specType = type;
      console.log(`切换到${type === 0 ? '单规格' : '多规格'}`);
      if (type === 0) {
        this.selectedSpecGroups = [];
        this.multipleSpecTableData = [];
      }
    },
    // 加载商品规格
    loadProductSpecs() {
      if (!this.selectedSpec) {
        this.selectedSpecGroups = [];
        this.multipleSpecTableData = [];
        return;
      }

      // 查找对应商品类型的规格数据
      const productSpec = this.cascaderAttrData.find(item => item.id === this.selectedSpec);

      if (productSpec) {
        // 清空现有规格
        this.selectedSpecGroups = [];

        // 添加从后端获取的规格
        productSpec.children.forEach(child => {
          this.selectedSpecGroups.push({
            spec: child.value.toString(),
            values: child.detail.map(value => value.toString())
          });
        });

        // 生成表格数据
        this.generateMultipleTableData();
        this.$message.success(`已加载"${productSpec.ruleName}"的规格`);
      }
    },

    confirmSpec() {
      if (!this.selectedSpec) {
        this.$message.warning('请选择规格');
        this.showSpecTable = false;
        return;
      }
      //生成规格数据
      this.loadProductSpecs();
      this.showSpecTable = true;
    },

    openAddSpecDialog() {
      this.addSpecDialogVisible = true;
      this.addSpecForm = {
        spec: '',
        value: ''
      };
    },

    confirmAddSpec() {
      const { spec, value } = this.addSpecForm;

      if (!spec || !value) {
        this.$message.warning('规格和规格值不能为空');
        return;
      }

      // 检查是否已存在该规格
      const existIndex = this.selectedSpecGroups.findIndex(
        group => group.spec === spec
      );

      if (existIndex !== -1) {
        // 已存在该规格，添加新规格值
        this.selectedSpecGroups[existIndex].values.push(value);
      } else {
        // 添加新规格
        this.selectedSpecGroups.push({
          spec,
          values: [value]
        });
      }

      this.addSpecDialogVisible = false;
      this.generateMultipleTableData();
    },

    handleAddSpecClose(done) {
      this.addSpecDialogVisible = false;
      done();
    },

    openAddSpecValueDialog(groupIndex) {
      this.currentGroupIndex = groupIndex;
      this.addSpecValueDialogVisible = true;
      this.addSpecValueForm = {
        value: ''
      };
    },

    confirmAddSpecValue() {
      const { value } = this.addSpecValueForm;

      if (!value) {
        this.$message.warning('规格值不能为空');
        return;
      }

      if (this.currentGroupIndex !== -1) {
        this.selectedSpecGroups[this.currentGroupIndex].values.push(value);
        this.generateMultipleTableData();
      }

      this.addSpecValueDialogVisible = false;
      this.currentGroupIndex = -1;
    },

    handleAddSpecValueClose(done) {
      this.addSpecValueDialogVisible = false;
      done();
    },

    // 删除规格值
    removeSpecValue(groupIndex, valueIndex) {
      this.selectedSpecGroups[groupIndex].values.splice(valueIndex, 1);

      // 如果规格值为空，移除该规格
      if (this.selectedSpecGroups[groupIndex].values.length === 0) {
        this.selectedSpecGroups.splice(groupIndex, 1);
      }

      this.generateMultipleTableData();
    },

    // 删除整个规格组
    removeSpecGroup(groupIndex) {
      this.deletingIndex = groupIndex;
      this.deletingSpec = this.selectedSpecGroups[groupIndex].spec;
      this.deleteDialogVisible = true;
    },

    confirmDeleteSpec() {
      if (this.deletingIndex !== -1) {
        this.selectedSpecGroups.splice(this.deletingIndex, 1);
        this.generateMultipleTableData();
        this.$message.success(`已删除规格"${this.deletingSpec}"`);
      }

      this.deleteDialogVisible = false;
      this.deletingIndex = -1;
      this.deletingSpec = '';
    },

    handleDeleteClose(done) {
      this.deleteDialogVisible = false;
      this.deletingIndex = -1;
      this.deletingSpec = '';
      done();
    },

    generateMultipleTableData() {
      if (this.selectedSpecGroups.length === 0) {
        this.multipleSpecTableData = [];
        return;
      }

      // 生成所有规格组合
      let combinations = [{}];

      this.selectedSpecGroups.forEach(group => {
        const newCombinations = [];

        combinations.forEach(comb => {
          group.values.forEach(value => {
            newCombinations.push({
              ...comb,
              [group.spec]: value
            });
          });
        });
        combinations = newCombinations;
      });

      // 为每个组合添加默认值
      this.multipleSpecTableData = combinations.map(comb => ({
        ...comb, // 规格属性直接作为key，保证表格渲染
        suk: comb, // 保留suk对象
        tableImage: "",
        price: 0,
        cost: 0,
        otPrice: 0,
        stock: 0,
        weight: 0,
        volume: 0
      }));
    },

    handleAttrData() {
      ProductRuleApi.getProductRulePage(null).then((res) => {
        // 对返回的属性数据按 id 去重
        const uniqueAttrOptions = res.data.list.filter(
          (item, index, self) =>
            index === self.findIndex((t) => t.id === item.id)
        );
        // 转换为级联结构
        this.cascaderAttrData = uniqueAttrOptions.map(item => {
          let children = [];
          if (item.ruleValue && item.ruleValue !== 'undefined' && item.ruleValue !== 'null') {
            try {
              children = JSON.parse(item.ruleValue).map(child => ({
                value: child.value,
                detail: child.detail
              }));
            } catch (e) {
              children = [];
            }
          }
          return {
            id: item.id,
            ruleName: item.ruleName,
            children: children
          };
        });
        console.log('级联数据:', this.cascaderAttrData);
      });
    },
    //获取商品分类
    getCategoryList() {
      CategoryApi.getCategoryList({ status: 1 }).then((res) => {
        // 转换数据为级联结构
        this.categoryOption = this.buildCascaderOptions(res.data);
      }).catch((error) => {
        this.$message.error("获取分类数据失败，请刷新页面重试");
        this.categoryOption = [];
      });
    },
    handleCategoryChange(value) {
      if (value && value.length > 0) {
        const flatIds = value.flat();
        // 去重
        const uniqueIds = [...new Set(flatIds)];
        this.productForm.cateId = uniqueIds.join(',');
      } else {
        this.productForm.cateId = "";
      }
    },
    /**
     * 构建级联选择器所需的层级结构
     */
    buildCascaderOptions(list) {
      // 1. 筛选顶级分类（pid=0）
      const rootCategories = list.filter((category) => category.pid === 0);
      // 2. 递归构建子分类
      const buildChildren = (parentId, level = 1) => {
        // 获取当前层级的子分类
        const children = list
          .filter((category) => category.pid === parentId)
          .map((category) => {
            // 构建基础结构
            const option = {
              value: category.id,
              label: category.name,
            };
            // 递归查找子分类，不限制层级
            const childOptions = buildChildren(category.id, level + 1);
            // 只有当子分类存在时才添加children属性
            if (childOptions && childOptions.length > 0) {
              option.children = childOptions;
            }
            return option;
          });
        return children;
      };
      // 3. 组装顶级分类及其子分类
      return rootCategories.map((category) => {
        const option = {
          value: category.id,
          label: category.name,
        };
        // 构建子分类
        const children = buildChildren(category.id, 1);
        // 只有当子分类存在时才添加children属性
        if (children && children.length > 0) {
          option.children = children;
        }
        return option;
      });
    },
    // 下一步按钮逻辑
    handleNext() {
      if (this.activeStep === 0) {
        // 步骤 1 切换到步骤 2 前，校验表单
        this.$refs.productFormRef.validate((valid) => {
          if (valid) {
            this.activeStep++;
          } else {
            this.$message.warning("请完成必填信息");
            return false;
          }
        });
      } else {
        this.activeStep++;
      }
    },
    // 上一步按钮逻辑
    handlePrev() {
      this.activeStep--;
    },
    // 提交按钮逻辑
    handleSubmit() {
      this.$confirm("确认提交表单？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          // 处理图片数据格式转换
          const submitData = { ...this.productForm };
          // 将image数组转换为字符串（取第一个元素）
          if (Array.isArray(submitData.image)) {
            submitData.image = submitData.image.length > 0 ? submitData.image[0] : '';
          }
          // 将sliderImage数组转换为字符串（用逗号连接）
          if (Array.isArray(submitData.sliderImage)) {
            submitData.sliderImage = submitData.sliderImage.join(',');
          }

          //单规格提交
          if (this.productForm.specType === 0) {
            submitData.price = this.tableData[0].price;//商品价格
            submitData.cost = this.tableData[0].cost;//成本价
            submitData.otPrice = this.tableData[0].otPrice;//市场价
            submitData.stock = this.tableData[0].stock;//库存

            //提交商品信息
            ProductApi.createProduct(submitData).then(res => {
              //提交商品规格
              const attrData = {
                productId: res.data,
                attrName: "规格",
                attrValues: "默认",
              }
              ProductApi.createProductAttr(attrData);

              //提交商品规格值
              const attrValueData = {
                productId: res.data,
                suk: "默认",
                stock: this.tableData[0].stock,
                price: this.tableData[0].price,
                image: Array.isArray(this.tableData[0].tableImage) ? this.tableData[0].tableImage[0] || '' : this.tableData[0].tableImage,
                cost: this.tableData[0].cost,
                otPrice: this.tableData[0].otPrice,
                weight: this.tableData[0].weight,
                volume: this.tableData[0].volume,
                attrValue: "{\"规格\":\"默认\"}"
              }
              ProductApi.createProductAttrValue(attrValueData);

              //提交商品详情
              const detailData = {
                productId: res.data,
                description: Array.isArray(this.detailImage) ? this.detailImage.join(',') : this.detailImage
              }
              ProductApi.createProductDetail(detailData);
              this.$message.success("商品新增成功！");
            }).catch(err => {
              this.$message.error("商品新增失败！");
            })
          } else {
            //多规格提交
            if (this.multipleSpecTableData && this.multipleSpecTableData.length > 0) {
              // 过滤掉无效价格（如null/undefined/NaN）
              const validRows = this.multipleSpecTableData.filter(row => typeof row.price === 'number' && !isNaN(row.price));
              if (validRows.length > 0) {
                // 找到最低售价的那条数据
                const minPriceRow = validRows.reduce((min, row) => row.price < min.price ? row : min, validRows[0]);
                submitData.price = minPriceRow.price;//商品价格
                submitData.cost = minPriceRow.cost;//成本价
                submitData.otPrice = minPriceRow.otPrice;//市场价
                submitData.stock = minPriceRow.stock;//库存
              }
            }

            //提交商品信息
            ProductApi.createProduct(submitData).then(res => {
              //提交商品规格
              this.selectedSpecGroups.forEach(group => {
                const attrData = {
                  productId: res.data,
                  attrName: group.spec,
                  attrValues: group.values.join(','),
                }
                ProductApi.createProductAttr(attrData);
              });

              //提交商品规格值
              this.multipleSpecTableData.forEach(row => {
                // 获取每个规格的值
                const specValues = this.selectedSpecGroups.map(group => row.suk[group.spec]);
                // 拼接成字符串
                const sukStr = specValues.join(',');

                const attrValueData = {
                  productId: res.data,
                  suk: sukStr,
                  stock: row.stock,
                  price: row.price,
                  image: Array.isArray(row.tableImage) ? row.tableImage[0] || '' : row.tableImage,
                  cost: row.cost,
                  otPrice: row.otPrice,
                  weight: row.weight,
                  volume: row.volume,
                  attrValue: JSON.stringify(row.suk)
                }
                ProductApi.createProductAttrValue(attrValueData);
              });

              //提交商品详情
              const detailData = {
                productId: res.data,
                description: Array.isArray(this.detailImage) ? this.detailImage.join(',') : this.detailImage
              }
              ProductApi.createProductDetail(detailData);
              this.$message.success("商品新增成功！");
            }).catch(err => {
              this.$message.error("商品新增失败！");
            })
          }
          // 跳转回商品首页
          this.$router.push('/store/storeproduct');
        })
        .catch(() => {
          this.$message.info("已取消提交");
        });
    },
    /** 重置 */
    reset() {
      // 重置步骤
      this.activeStep = 0;

      // 重置商品表单
      this.productForm = {
        activity: "",//活动优先级
        isHot: 0,//是否热卖
        isNew: 0,//首发新品
        isBest: 0,//精品推荐
        isBenefit: 0,//促销单品
        isGood: 0,//热门榜单
        ficti: 0,//虚拟销量
        giveIntegral: 0,//积分
        sort: 0,//排序
        storeName: "",//商品名称
        cateId: "",//商品分类
        keyword: "",//商品关键字
        unitName: "",//单位
        storeInfo: "",//商品简介
        image: [],//商品封面图 - 初始化为数组
        sliderImage: [],//商品轮播图 - 初始化为数组
        specType: 0,//商品规格
        vipPrice: 0,//vip价格
        postage: 0,//运费
        isPostage: 0,//是否包邮
        price: 0,//商品价格
        cost: 0,//成本价
        otPrice: 0,//市场价
        stock: 0,//库存
      };

      // 重置单规格数据
      this.tableData = [
        {
          tableImage: "",//单规格图片 - 初始化为数组
          price: 0,//商品价格
          cost: 0,//成本价
          otPrice: 0,//市场价
          stock: 0,//库存
          productNo: null,//商品编号
          weight: 0,//重量
          volume: 0,//体积
        }
      ];

      // 重置多规格数据
      this.multipleSpecTableData = [];

      // 重置商品详情
      this.detailImage = [];

      // 重置规格相关数据
      this.selectedSpec = '';
      this.selectedSpecGroups = [];
      this.recommendTypes = [];

      // 重置按钮列表顺序
      this.buttonList = [
        { label: '默认', type: 'danger', key: 0 },
        { label: '秒杀', type: 'primary', key: 1 },
        { label: '砍价', type: 'success', key: 2 },
        { label: '拼团', type: 'warning', key: 3 }
      ];

      // 重置表单验证
      if (this.$refs.productFormRef) {
        this.$refs.productFormRef.resetFields();
      }
    },
    numberKeydown(e) {
      // 允许的按键
      const allowKeys = [
        ...Array.from({ length: 10 }, (_, i) => i + 48), // 0-9 主键盘
        ...Array.from({ length: 10 }, (_, i) => i + 96), // 0-9 小键盘
        8, 9, 13, 27, 46, // Backspace, Tab, Enter, Esc, Delete
        37, 38, 39, 40,   // 方向键
        110, 190          // 小数点
      ];
      // 禁止 e, +, - 等
      if (!allowKeys.includes(e.keyCode)) {
        e.preventDefault();
      }
      // 只允许一个小数点
      if ((e.key === '.' || e.keyCode === 110 || e.keyCode === 190) && e.target.value.includes('.')) {
        e.preventDefault();
      }
    },
    handleBatchSet() {
      this.multipleSpecTableData.forEach(row => {
        Object.keys(this.batchForm).forEach(key => {
          if (this.batchForm[key] !== null && this.batchForm[key] !== '' && this.batchForm[key] !== undefined) {
            if (key === 'tableImage' && Array.isArray(this.batchForm[key])) {
              row[key] = [...this.batchForm[key]];
            } else {
              row[key] = this.batchForm[key];
            }
          }
        });
      });
      this.$message.success('批量设置成功！');
    },
  },
};
</script>
<style scoped>
.product-steps-container {
  padding: 20px;
}

.steps-content {
  margin-top: 20px;
  border-radius: 4px;
  padding: 20px;
  background-color: #fff;
}

.el-upload {
  margin-top: 10px;
}

.el-table {
  --el-table-header-text-color: #666;
}

:deep(.el-upload--picture-card) {
  width: 60px !important;
  height: 60px !important;
  line-height: 65px !important;
}

:deep(.el-upload-list--picture-card .el-upload-list__item) {
  width: 60px !important;
  height: 60px !important;
}

:deep(.el-upload__tip) {
  display: none !important;
}

.spec-list {
  margin-left: 120px;
}

.spec-name {
  margin: 0px;
}

.spec-tag {
  margin-bottom: 20px;
  margin-right: 10px;
}

.product-info {
  padding: 20px;
}


.drag-button-sort {
  padding: 20px;
}

.title {
  margin-bottom: 8px;
  font-size: 14px;
}

.button-group {
  display: inline-flex;
  align-items: center;
}

.tip {
  margin-top: 8px;
  font-size: 12px;
  color: #999;
}

.center-table {
  display: flex;
  justify-content: center;
  width: 100%;
}

.large-upload :deep(.el-upload--picture-card) {
  width: 200px !important;
  height: 200px !important;
  line-height: 200px !important;
  font-size: 40px !important;
}

.large-upload :deep(.el-upload-list--picture-card .el-upload-list__item) {
  width: 200px !important;
  height: 200px !important;
}
</style>